<template>
  <BreadCrumb>
    <template #default>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ name: 'DyjNoticeList' }">公告管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{ textMap[props.type] }}公告</el-breadcrumb-item>
      </el-breadcrumb>
    </template>
  </BreadCrumb>
  <PageListContainer class="base-block notice-list">
    <k-form
      ref="formRef"
      :model="state.model"
      :rules="rules"
      label-width="90px"
    >
      <el-form-item label="公告标题" prop="title">
        <el-input v-model="state.model.title" :disabled="props.type === 'check'" clearable placeholder="请填写公告标题" style="width: 60%" maxlength="20" />
      </el-form-item>
      <el-form-item label="公告类型" prop="type">
        <el-select v-model="state.model.type" :disabled="props.type === 'check' || props.type === 'edit'" placeholder="请选择公告类型" style="width: 320px">
          <el-option
            v-for="item in typeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发送对象" prop="send_object">
        <el-select v-model="state.model.send_object" :disabled="props.type === 'check' || props.type === 'edit'" placeholder="请选择发送对象" style="width: 320px">
          <el-option
            v-for="item in objectOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发送时间" prop="publish_time">
        <el-date-picker
          v-model="state.model.publish_time"
          :disabled="props.type === 'check' || props.type === 'edit'"
          type="datetime"
          value-format="X"
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="请选择发送时间"
          :disabled-date="rangDisabled"
          :clearable="false"
          style="width: 320px"
        />
      </el-form-item>
      <el-form-item label="公告内容" prop="content">
        <ContentEditor v-if="props.type !== 'check'" v-model:html="state.model.content" />
        <div
          v-else
          class="notice-content"
          v-html="state.model.content"
        ></div>
      </el-form-item>
      <el-form-item label-width="86px">
        <template v-if="props.type !== 'check'">
          <el-button :disabled="state.loading" @click="methods.resetModel">清空</el-button>
          <el-button :loading="state.loading" type="primary" @click="methods.onSubmit">发布</el-button>
        </template>
        <el-button v-else @click="goBackList">返回消息列表</el-button>
      </el-form-item>
    </k-form>
  </PageListContainer>
</template>

<script setup lang="ts">
import dayjs from 'dayjs';
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useForm } from '@crud/index';
import { toolReplaceEditorInput, isEmpty } from '@/utils';
import { add, edit, getDetail } from '@/api/crm-content/notice';
import ContentEditor from '@/components/base-editor/index.vue';
import BreadCrumb from '@/components/base-bread-crumb/index.vue';
defineOptions({ name: 'DyjNoticeAdd' });
const route = useRoute();
const router = useRouter();
const props = route.query as Record<string, any>;
// options
const typeOptions = [{
  label: '公告',
  value: 1
},
{ label: '行业报告',
  value: 2 }];
const objectOptions = [
  {
    label: '全部',
    value: 0
  },
  { label: '大赢加',
    value: 1 },
  { label: '考古加',
    value: 2 }
];
// 返回
const goBackList =() => {
  router.push({ name: 'DyjNoticeList' });
};
const rangDisabled = (current: any) => {
  return dayjs(current).isBefore(dayjs().startOf('day'));
};
const textMap = {
  create: '新增',
  edit: '编辑',
  check: '查看'
};
const formRef = ref();
// 判断富文本编辑器输入是否为空或回车
const validateContent = (rule: any, value: any, callback: any) => {
  const val = toolReplaceEditorInput(value);
  if (isEmpty(val)) {
    callback(new Error('请填写公告内容'));
  } else if (val.length < 5) {
    callback(new Error('公告内容不能少于5个字符'));
  } else if (val.length > 10000) {
    callback(new Error('公告内容不能超过10000个字符'));
  } else {
    callback();
  }

};
const rules = {
  title: [{ required: true, message: '请填写消息标题' }],
  type: [{ required: true, message: '请选择公告类型' }],
  send_object: [{ required: true, message: '请选择发送对象' }],
  publish_time: [{ required: true, message: '请选择发送时间' }],
  content: [
    { required: true, validator: validateContent }
  ]
};
const { state, ...methods } = useForm({
  formRef,
  model: {
    title: '',
    type: 1,
    send_object: 0,
    publish_time: dayjs().add(1, 'h').unix().valueOf(),
    content: ''
  },
  onSubmit: async (model: any, mode = 0) => {
    let validate = false;
    if (formRef?.value?.validate) {
      validate = await formRef.value.validate();
    }
    if (!validate) return;
    state.loading = true;
    if (props.type==='create') {
      const res = await add(model).finally(() => state.loading = false);
      if (res.err) return;
      ElMessage.success('发布成功');
      router.push({ name: 'DyjNoticeList' });
    } else if (props.type==='edit') {
      if (!props.id) return;
      const res = await edit(props.id, model).finally(() => state.loading = false);
      if (res.err) return;
      ElMessage.success('编辑成功');
      router.push({ name: 'DyjNoticeList' });
    }

  }
});

// 获取详情
const getDetailInfo = async () => {
  const res = await getDetail(props.id);
  const { data } = res;
  if (data) {
    state.model = {
      ...state.model,
      ...data,
      publish_time: data.publish_time
    };
  }
};
// 编辑
if (props.type === 'edit' || props.type === 'check') {
  getDetailInfo();
}
</script>
<style lang="scss" scoped>
.notice-content {
  width: 80%;
  min-height: 300px;
  padding: 20px;
  word-break: break-all;
  white-space: pre-wrap;
  border: solid 1px #ccc;
}
</style>
